package mest.controller.cxj;

import com.alibaba.fastjson.JSON;
import mest.VO.cxj.RemarkVO;
import mest.entity.remark;
import mest.service.cxj.RemarkService;
import mest.service.system.DBService;
import mest.util.DateUtil;
import mest.util.ResultObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("remark")
@CrossOrigin
public class RemarkController {

    @Autowired
    private RemarkService remarkService;

    @Autowired
    private DBService dbService;

    /**
     * 用户添加评论
     */
    @PostMapping("add")
    public String add(@RequestBody remark r) {
        String theirDb=dbService.getCompanyDB();//数据库名称
        Integer userId=dbService.getUserId(); //操作人ID
        ResultObj resultObj = null;
        try {
            r.setEfId(userId); //默认当前员工ID
            r.setTime(DateUtil.getDateTimeToDate()); //获取系统时间
            if (remarkService.insertRemark(r,theirDb) > 0) {
                resultObj = ResultObj.builder().code(0).msg("添加成功").build();
            } else {
                resultObj = ResultObj.builder().code(-1).msg("添加失败").build();
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultObj = ResultObj.builder().code(-2).msg("系统异常,请联系管理员").build();
        }
        return JSON.toJSONString(resultObj);
    }

    /**
     * 查看评论
     * @return
     */
    @GetMapping("selectAll")
    public String selectAll(@RequestParam(required = false) Integer poId) {
        ResultObj resultObj = null;
        String theirDb=dbService.getCompanyDB();
        try {
            List<RemarkVO> remarkVOList = remarkService.selectAllRemark(poId,theirDb);
            Integer count = remarkService.selectCountRemark(poId,theirDb);
            resultObj = new ResultObj(0, "success", count, remarkVOList);
        } catch (Exception e) {
            e.printStackTrace();
            resultObj = ResultObj.builder().code(-2).msg("系统异常,请联系管理员").build();
        }
        return JSON.toJSONString(resultObj);
    }

}
